from app.models import db
from app.utils.logger import logger

class BaseService:
    """基础服务类，所有服务的父类"""
    
    def __init__(self, model=None):
        """初始化服务，指定对应的模型"""
        self.model = model
    
    def get_by_id(self, item_id):
        """根据ID获取记录"""
        if not self.model:
            raise ValueError("未指定模型类")
            
        try:
            return self.model.query.filter_by(
                id=item_id, 
                is_active=True
            ).first()
        except Exception as e:
            logger.error(f"获取记录失败: {str(e)}")
            return None
    
    def get_all(self, page=1, per_page=20):
        """获取所有记录，支持分页"""
        if not self.model:
            raise ValueError("未指定模型类")
            
        try:
            pagination = self.model.query.filter_by(
                is_active=True
            ).paginate(page=page, per_page=per_page)
            return pagination
        except Exception as e:
            logger.error(f"获取记录列表失败: {str(e)}")
            return None
    
    def create(self, **kwargs):
        """创建新记录"""
        if not self.model:
            raise ValueError("未指定模型类")
            
        try:
            item = self.model(** kwargs)
            db.session.add(item)
            db.session.commit()
            return item
        except Exception as e:
            db.session.rollback()
            logger.error(f"创建记录失败: {str(e)}")
            return None
    
    def update(self, item_id, **kwargs):
        """更新记录"""
        item = self.get_by_id(item_id)
        if not item:
            return None
            
        try:
            for key, value in kwargs.items():
                if hasattr(item, key):
                    setattr(item, key, value)
            
            db.session.commit()
            return item
        except Exception as e:
            db.session.rollback()
            logger.error(f"更新记录失败: {str(e)}")
            return None
    
    def delete(self, item_id):
        """逻辑删除记录"""
        item = self.get_by_id(item_id)
        if not item:
            return False
            
        try:
            item.is_active = False
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            logger.error(f"删除记录失败: {str(e)}")
            return False
